package com.fesine.other;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @description: 类描述
 * @author: Fesine
 * @createTime:2016/10/31 11:11
 * @update:修改内容
 * @author: Fesine
 * @updateTime:2016/10/31 11:11
 */
public class ProviderAndConsumer {
    private int[] queen = new int[100];
    private int count=1;
    private int proIndex=0;
    private Object proLock = new Object();

    private int conIndex=0;
    private Object conLock = new Object();
    public void provider() {
        synchronized (proLock) {
            if (proIndex == queen.length) {
                proIndex=0;
            }
            if (0 != queen[proIndex]) {
                System.out.println("队列已满。。。");
                return;
            }
            queen[proIndex++] = count++;
            System.out.println("生产。。。"+count);
        }
    }

    public int consumer() {
        synchronized (conLock) {
            if (conIndex == queen.length) {
                conIndex=0;
            }
            if (0 == queen[conIndex]) {
                System.out.println("队列已空。。。");
            }
            return queen[conIndex++];
        }
    }

    public static void main(String[] args) {
        final ProviderAndConsumer pc = new ProviderAndConsumer();
        ExecutorService ptp = Executors.newFixedThreadPool(3);
        ExecutorService ctp = Executors.newFixedThreadPool(2);
        for (int i = 0; i < 30; i++) {
            ptp.execute(new Thread(new Runnable() {
                @Override
                public void run() {
                    pc.provider();
                }
            }));
        }

        for (int j = 0; j < 31; j++) {
            ctp.execute(new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println(pc.consumer());
                }
            }));
        }
    }
}
